<template>
  <div>
    <div class="page-breadcrumb-wrap">
      <el-card class="page-breadcrumb">
        <span class="breadcrumb-button" @click="goBack">审批进展</span>
        <span class="breadcrumb-line">/</span>
        <span class="breadcrumb-active">审批</span>
      </el-card>
    </div>
    <div class="detail-box">
      <el-card>
        <el-form ref="form" :model="dataForm" label-width="120px" :style="{'height': formHeight + 'px','overflow-y': 'auto','position': 'relative','overflow-x': 'hidden'}">
          <div class="form-header">
            <span class="form-title">审批详情</span>
            <el-button type="primary" @click="goBack" plain>返 回</el-button>
          </div>
          <el-row>
            <el-col :span="8" class="mt10">
              <el-form-item label="项目:">
                {{ dataForm.lineName }}
              </el-form-item>
            </el-col>
            <el-col :span="8" class="mt10">
              <el-form-item label="分部:">
                {{ dataForm.lotName }}
              </el-form-item>
            </el-col>
            <el-col :span="8" class="mt10">
              <el-form-item label="工区:">
                {{ dataForm.workArea }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审批名称:">
                {{ dataForm.projectName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="权属单位:">
                {{ dataForm.ownershipUnit }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="权属单位审批人:">
                {{ dataForm.linkName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系方式:">
                {{ dataForm.linkPhone }}
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-header mt10">
            <span class="form-title">关联审批流程</span>
          </div>
          <el-row>
            <el-col :span="8" class="mt10">
              <el-form-item label="模型编码:">
                {{ dataForm.moduleCode }}
              </el-form-item>
            </el-col>
            <el-col :span="8" class="mt10">
              <el-form-item label="模型名称:">
                {{ dataForm.moduleName }}
              </el-form-item>
            </el-col>
            <el-col :span="8" class="mt10">
              <el-form-item label="生效版本:">
                {{ dataForm.version }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="流程描述:">
                {{ dataForm.remark }}
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-header mt10" style="border-bottom:none;">
            <span class="form-title">设计方案</span>
          </div>
          <div class="center-card">
            <div class="card-left">
              <span class="form-sub-title">涉敏区域</span>
              <div class="card-left-body">
                <el-col :span="24">
                  <el-form-item label="BIM模型:" label-width="120px">
                    {{ dataForm.sensitiveAreaBim }}
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="GIS边界文件:" label-width="120px">
                    <div style="height: 100px; overflow: auto;overflow-x: hidden;">
                      <div class="file-item" v-for="item in dataForm.gisFiles" :key="item.fileId">
                        <img src="../../../../assets/icon/antFill-file-excel.png" class="file-item-icon" alt="" />
                        <div class="file-item-content">
                          <div class="file-item-text" :title="item.fileName">{{ item.fileName }}</div>
                          <div class="file-item-button">
                            <el-button type="text" @click="download(item)">下载</el-button>
                            <el-button type="text" @click="filePreview(item)">预览</el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </div>
            </div>
            <div class="card-line"></div>
            <div class="card-center">
              <span class="form-sub-title">施工设计</span>
              <div class="card-right-body">
                <el-col :span="24">
                  <el-form-item label="BIM模型:" label-width="120px">
                    {{ dataForm.constructDesignBim }}
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="施工方案文件:" label-width="120px">
                    <div style="height: 100px; overflow: auto;overflow-x: hidden;">
                      <div class="file-item" v-for="item in dataForm.schemeFiles" :key="item.fileId">
                        <img src="../../../../assets/icon/antFill-file-excel.png" class="file-item-icon" alt="" />
                        <div class="file-item-content">
                          <div class="file-item-text" :title="item.fileName">{{ item.fileName }}</div>
                          <div class="file-item-button">
                            <el-button type="text" @click="download(item)">下载</el-button>
                            <el-button type="text" @click="filePreview(item)">预览</el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </div>
            </div>
          </div>
          <div class="form-header" style="margin-top: 40px">
            <span class="form-title">审批进度</span>
            <el-button type="text" @click="viewFlowPicture">查看流程图</el-button>
          </div>
          <div style="padding: 10px">
            <el-steps :active="active" align-center>
              <el-step
                v-for="(item, index) in stepList"
                :title="item.taskName + ' ' + item.userName"
                :key="index"
                :icon="!item.endTime ? 'el-icon-info' : 'el-icon-circle-check'"
              >
                <template #description>
                  <div>
                    <div style="color: #303133;">{{ item.endTime }}</div>
                    <el-popover placement="top" trigger="click">
                      <div class="file-item" v-for="ele in item.attachments" :key="ele.fileId">
                        <img src="../../../../assets/icon/antFill-file-excel.png" class="file-item-icon" alt="">
                        <div class="file-item-content">
                          <div class="file-item-text" :title="ele.originalFileName">{{ ele.originalFileName }}</div>
                          <div class="file-item-button">
                            <el-button type="text" @click="download(ele)">下载</el-button>
                            <el-button type="text" @click="filePreview(ele)">预览</el-button>
                          </div>
                        </div>
                      </div>
                      <el-button slot="reference" v-if="item.attachments.length > 0" type="text">查看</el-button>
                    </el-popover>
                  </div>
                  <div :title="item.comment" style="color: red;width:100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{{ item.comment }}</div>
                </template>
              </el-step>
            </el-steps>
          </div>
          <div class="footer-operation">
          </div>
          <div class="footer-operation1">
            <el-button type="danger" plain @click="handlereject('reject')">驳 回</el-button>
            <el-button type="primary" @click="handleApproved('approved')">通 过</el-button>
            <el-button type="info" plain @click="handleApprovedFile">审批档案</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
    <flow-picture ref="flowPictureRef" />
    <el-dialog title="审核驳回" :visible.sync="dialogVisible" width="40%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="驳回原因" prop="comment">
          <el-input
            v-model="form.comment"
            placeholder="请输入驳回原因"
            type="textarea"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button type="danger" @click="rejectSubmit">驳 回</el-button>
      </span>
    </el-dialog>
    <el-dialog title="审核通过" :visible.sync="dialogVisible1" width="40%">
      <el-form ref="approverForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="下一步审批人" v-if="approvalContentInfo.ifNextApprover" prop="nextApprover">
          <el-button type="primary" @click="selectUserBtn" style="margin-right: 10px" size="mini">选择审批人</el-button>
          <el-tag v-if="selectUserObj.id" effect="plain">
            {{ this.selectUserObj.name }}
          </el-tag>
        </el-form-item>
        <el-form-item label="档案">
          <div v-for="(item, i) in approvalContentInfo.attachments" :key="i" style="margin-top: 10px">
            <el-upload
              :action="action"
              :headers="headers"
              :data="fileParams"
              multiple
              :before-upload="(file, fileList) => handleBeforeUpload(file, fileList, item)"
              :limit="5"
              :accept="item.fileType"
              :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item)"
              :on-remove="(file, fileList) => handleRemove(file, fileList, item)"
              :on-exceed="handleExceed"
            >
              <el-button type="primary"><i class="el-icon-upload"></i> {{ item.fileName }}</el-button>
              <div slot="tip" class="el-upload__tip" style="color: #aeaeb2">支持格式：{{ item.fileType }}</div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">关 闭</el-button>
        <el-button type="primary" @click="approvalSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="候选用户" :visible.sync="userOpen" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :md="6" :sm="24" class="leftOrgTree">
          <cr-org-tree v-model="orgObj" :treeHeight="leftOrgTreeHeight"></cr-org-tree>
        </el-col>
        <el-col :md="18" :sm="24">
          <div class="table-page-search-wrapper">
            <!--搜索-->
            <el-form inline :model="userQueryParams" @submit.native.prevent>
              <el-row :gutter="48">
                <!-- 搜索item项 -->
                <el-col :md="8" :sm="24">
                  <el-form-item label="姓名" prop="keyword">
                    <el-input v-model.trim="userQueryParams.name" placeholder="请输入姓名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :md="8" :sm="24">
                  <el-form-item label="用户名" prop="keyword">
                    <el-input v-model.trim="userQueryParams.userName" placeholder="请输入用户名" clearable />
                  </el-form-item>
                </el-col>
                <!-- 查询按钮 -->
                <el-col :md="8" :sm="24">
                  <el-form-item>
                    <span class="table-page-search-submitButtons">
                      <el-button type="primary" @click="handleSearch">查 询</el-button>
                      <el-button style="margin-left: 8px" @click="resetQuery">重 置</el-button>
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-table
              ref="multipleTable"
              height="350"
              stripe
              :data="userTableList"
              row-key="id"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" reserve-selection />
              <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip />
              <el-table-column label="用户名" align="center" prop="userName" show-overflow-tooltip />
              <el-table-column label="机构名称" align="center" prop="orgName" show-overflow-tooltip />
              <el-table-column label="全路径" align="center" prop="fullNames" show-overflow-tooltip />
            </el-table>
            <pagination
              :total="userTotal"
              :page.sync="userQueryParams.pageNo"
              :limit.sync="userQueryParams.pageSize"
              @pagination="getUserTableList"
            />
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleTaskUserComplete">确 定</el-button>
      </div>
    </el-dialog>
    <approval-file ref="approvalFileRef"></approval-file>
  </div>
</template>
<script>
import { getDetail, getModuleById, download } from '@/api/constructionScheme'
import { getProcessHistory, approvalContent, approval, getUserList } from '@/api/constructionSchemeApprovalProgress'
import FlowPicture from '@/views/designingScheme/designingScheme/components/FlowPicture.vue'
import { getToken } from '@/utils/auth'
import ApprovalFile from '@/views/designingScheme/designingScheme/components/ApprovalFile.vue'
export default {
  name: 'SavePage',
  components: {
    FlowPicture,
    ApprovalFile
  },
  watch: {
    orgObj: {
      handler: function (newVal) {
        console.log(newVal, 'newVal')
        if (!newVal?.id) return
        this.userQueryParams.orgId = newVal.id
        this.getUserTableList()
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      action: process.env.VUE_APP_API_BASE_URL + '/bp-file-server/file/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileParams: {
        fileClassify: 'gz-metro'
      },
      dataForm: {},
      selectedUserDate: [],
      active: 1,
      stepList: [],
      dialogVisible: false,
      dialogVisible1: false,
      form: {
        comment: '',
        taskId: '',
        attachments: [],
        outcome: ''
      },
      rules: {
        comment: [
          { required: true, message: '驳回原因不能为空', trigger: 'blur' },
          { max: 100, message: '不能超过100个字符', trigger: 'blur' }
        ],
        nextApprover: [{ required: true, message: '下一步审批人不能为空', trigger: 'blur' }]
      },
      approvalContentInfo: {},
      orgObj: {},
      isAdvanced: false,
      leftOrgTreeHeight: 500,
      // 查询参数
      userQueryParams: {
        pageNo: 1,
        name: '',
        userName: '',
        mobile: '',
        pageSize: 10,
        orgId: ''
      },
      userOpen: false,
      userTotal: 0,
      userTableList: [],
      selectUserObj: {},
      formHeight: 500
    }
  },
    mounted () {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.setTableHeight)
    // 初始化表格高度
    this.setTableHeight()
  },
  methods: {
    handleApprovedFile () {
      this.$refs.approvalFileRef.open(this.dataForm.processInstanceId)
    },
    filePreview (item) {
      this.$filePreview(item)
    },
    setTableHeight () {
      this.$nextTick(() => {
        this.formHeight = document.body.offsetHeight - 160
      })
    },
    handleTaskUserComplete () {
      if (this.selectedUserDate <= 0) {
        return this.$message.error('请选择下一步审批人')
      }
      this.selectUserObj = this.selectedUserDate[0]
      this.form.nextApprover = this.selectUserObj.id
      this.userOpen = false
    },
    selectUserBtn () {
      this.userOpen = true
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection()
      })
    },
    handlereject (type) {
      this.form.outcome = type
      this.form.comment = ''
      this.dialogVisible = true
    },
    handleApproved (type) {
      this.form.outcome = type
      // 不用选下一步审批人及上传文件，直接走通过逻辑
      if (!this.approvalContentInfo.isAdvanced && this.approvalContentInfo.attachments.length === 0) {
        this.$confirm(`确定审批通过?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
        await approval(this.form)
        this.$message.success('操作成功')
        this.dialogVisible1 = false
        this.goBack()
        })
        .catch(() => {
          console.log('已取消')
        })
      } else {
        this.dialogVisible1 = true
      }
    },
    handleRemove (file, fileList) {
      console.log(file.response.data.fileId, fileList, this.form.attachments, '删除')
      const i = this.form.attachments.findIndex((v) => v.fileId === file.response.data.fileId)
      this.form.attachments.splice(i, 1)
    },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleSuccess (response, file, fileList, item) {
      // 将上传成功的文件添加到gisFiles数组中
      console.log(response.data, file, fileList, item, '上传成功')
      this.form.attachments.push({
        fileType: item.fileType,
        fileName: item.fileName,
        originalFileName: response.data.fileName,
        fileId: response.data.fileId
      })
    },
    approvalSubmit () {
      console.log(this.approvalContentInfo.attachments, this.form.attachments, '附件')
      for (let index = 0; index < this.approvalContentInfo.attachments.length; index++) {
        const item = this.approvalContentInfo.attachments[index]
        if (item.isRequire) {
          const findObj = this.form.attachments.find((v) => v.fileName === item.fileName)
          if (!findObj) return this.$message.error(`${item.fileName}不能为空`)
        }
      }
      this.$refs.approverForm.validate(async (valid) => {
        if (valid) {
          const res = await approval(this.form)
          console.log(res, 'res')
          this.$message.success('操作成功')
          this.dialogVisible1 = false
          this.goBack()
        }
      })
    },
    async rejectSubmit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await approval(this.form)
          console.log(res, 'res')
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.goBack()
        }
      })
    },
    async init (row) {
      console.log(row)
      const res = await getDetail({ schemeId: row.id })
      console.log(res, '详情')
      this.dataForm = res.data
      const result = await getModuleById({ modelId: this.dataForm.moduleId, versionId: res.data.versionId })
      this.dataForm.moduleName = result.data.moduleName
      this.dataForm.version = result.data.version
      this.dataForm.moduleCode = result.data.moduleCode
      this.dataForm.remark = result.data.remark
      this.$forceUpdate()
      const result1 = await getProcessHistory({ processId: res.data.processInstanceId })
      this.stepList = result1.data
      console.log(this.stepList, '审批进度')
      this.stepList.forEach((item, index) => {
        if (item.endTime) {
          this.active = index + 1
        }
        // if (this.stepList[this.stepList.length - 1].endTime) {
        //     this.active = this.stepList.length
        //   }
      })
      const result2 = await approvalContent({ processInstanceId: res.data.processInstanceId })
      this.approvalContentInfo = result2.data
      this.form.taskId = this.approvalContentInfo.taskId
      this.form.schemeId = row.id
    },
    goBack () {
      this.$emit('changeShowType', 1)
    },
    // 下载文件
    download (row) {
      download(row.fileId).then((res) => {
        console.log(res)
        const blob = new Blob([res.res])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url
        link.download = row.fileName // 重命名文件
        link.click()
        URL.revokeObjectURL(url) // 释放内
      })
    },
    // 查看流程图
    viewFlowPicture () {
      this.$nextTick(() => {
        this.$refs.flowPictureRef.init(this.dataForm.processInstanceId)
      })
    },
    // 重置
    resetQuery () {
      this.userQueryParams.name = ''
      this.userQueryParams.userName = ''
      this.userQueryParams.mobile = ''
      this.userQueryParams.pageNo = 1
      this.userQueryParams.pageSize = 10
      this.getUserTableList()
    },
    handleSearch () {
      this.userQueryParams.pageNo = 1
      this.getUserTableList()
    },
    handleBeforeUpload (file, fileList, item) {
      console.log(item.fileType, '文件类型')
      const fileType = {
        word: ['docx', 'doc', 'xlsx', 'xls', 'ppt', 'pptx', 'txt', 'pdf'],
        image: ['jpeg', 'png', 'gif', 'tif', 'jpg'],
        audioAndVideo: ['avi', 'mp4', 'mov', 'flv', 'wma', 'vlc', 'mp3', 'wav']
      }
      const fileTypeList = fileType[item.fileType]
      // 校检文件类型
      if (fileTypeList.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = fileTypeList.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${fileTypeList.join('/')}格式文件!`)
          return false
        }
      }
      return true
    },
    // 获取列表数据
    async getUserTableList () {
      console.log(this.userQueryParams, 'this.queryParams')
      const res = await getUserList(this.userQueryParams)
      this.userTableList = res.data.list
      this.userTotal = res.data.totalCount
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.selectedUserDate = selection
      if (selection.length > 1) {
        this.$refs.multipleTable.clearSelection() // 清空所有选择
        this.$refs.multipleTable.toggleRowSelection(selection.pop()) // 设置选择项
      }
    }
  }
}
</script>
<style scoped lang="scss">
.mt10 {
  margin-top: 10px;
}

.detail-box {
  padding: 10px;
  padding-top: 0;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.form-title {
  color: #101010;
  font-size: 16px;
  font-weight: bold;
}

.form-sub-title {
  margin-bottom: 10px;
  color: #101010;
  font-size: 15px;
  font-weight: bold;
}

.center-card {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-left {
  width: calc(49% - 21px);

  .card-left-body {
    padding: 10px 30px;
    height: 200px;
  }
}

.card-center {
  width: calc(49% - 21px);

  .card-center-body {
    padding: 10px 30px;
    height: 200px;
  }
}

.card-right {
  width: calc(33% - 21px);

  .card-right-body {
    padding: 10px 0;
    height: 200px;
  }
}

.card-line {
  margin: 0 20px;
  height: 180px;
  width: 1px;
  background: #ddd;
}
.file-item {
  display: flex;
  margin-bottom: 10px;
}

.file-item-icon {
  width: 40px;
  height: 50px;
}
.file-item {
  display: flex;
  margin-bottom: 10px;
}

.file-item-icon {
  width: 40px;
  height: 50px;
}
.file-item-content {
  margin-left: 10px;
  height: 50px;
   width: calc(100% - 45px);
  .file-item-text {
    height: 25px;
    font-weight: 700;
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .file-item-button {
    height: 25px;
  }
}

::v-deep .el-step__title.is-success {
  font-weight: 700;
  color: #303133;
}

::v-deep .el-step__head.is-process {
  color: #eca600;
}
.footer-operation {
  text-align: center;
  margin-top: 20px;
  height: 40px;
}
::v-deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
::v-deep .el-step__title.is-finish {
  font-weight: 700;
  color: #303133;
}
::v-deep .el-step__title.is-wait {
  font-weight: 700;
  color: #303133;
}
::v-deep .el-step__head.is-success {
  color: #409eff;
  border-color: #409eff;
}
::v-deep .el-icon-info {
  color: #eca600;
}

::v-deep .el-step__title {
  font-size: 14px;
}
::v-deep .el-step {
  margin-top: 20px;
  flex-basis: 20% !important;
  max-width: none !important;
}
::v-deep .el-steps {
  flex-wrap: wrap;
}
.footer-operation1 {
  z-index: 1;
  position: fixed;
  bottom: 25px;
  left: 50%;
}
</style>
